<template>
    <el-dialog :title="title" v-model="visible" width="480px" :close-on-click-modal="false" @close="emits('close')">
        <el-form ref="formRef"
                 :model="form"
                 :rules="formRules"
                 :label-width="120">
          
            <el-form-item label="账号名:" prop="account">
                <el-input v-model="form.account" placeholder="请设置账号名（仅支持数字/英文）"></el-input>
            </el-form-item>
            
            <el-form-item label="账号密码:" prop="password" v-if="props.state == 'add'">
                <el-input v-model="form.password" placeholder="请输入6-12位登录密码"></el-input>
            </el-form-item>
            <el-form-item label="姓名:" prop="name">
                <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="手机号码:" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请输入手机号码"></el-input>
            </el-form-item>
            <el-form-item label="角色:" prop="role_list">
                <el-select v-model="form.role_list" placeholder="请选择角色(可多选)" multiple>
                    <el-option v-for="(item,index) in roleList" :key="index" :label="item.role_name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="部门:" prop="dept_id">
                <el-tree-select v-model="form.dept_id" 
                                style="width:100%"
                                check-strictly
                                :data="departList" 
                                :render-after-expand="false"
                                :props="{
                                    label:'name',
                                    value:'id'
                                }"></el-tree-select>
            </el-form-item>
            <el-form-item label="是否启用" prop="enabled">
                <el-switch v-model="form.enabled"
                           :active-value="1"
                           :inactive-value="0"></el-switch>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="emits('close')">取 消</el-button>
                <el-button type="primary" @click="save(formRef)">确 定</el-button>
            </div>
        </template>
        
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed, nextTick, onMounted} from 'vue'
import { ElMessage } from 'element-plus'

import type { FormInstance, FormRules } from 'element-plus'

import { useRoute } from 'vue-router'

import { getAccountDetail, saveAccount, getRoleList, getDepartList } from 'services/setting'

import type {User} from '../../index'

const emits = defineEmits(['close', 'success'])

const route = useRoute()

const formRef = ref<FormInstance>()

const form = ref<User>({
    id: undefined,
    name: '',
    mobile: '',
    account: '',
    password: '',
    enabled:  1,
    dept_id:  undefined,
    role_list: [],
})

const checkPassword = (rule:any,value:any,callback:any) => {
    var reg = /(?!^[0-9]+$)(?!^[a-z]+$)(?!^[A-Z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]/

    if (value === '') {
        callback(new Error('请输入登录密码'))
    } else if (value.length < 6) {
        callback(new Error('密码最少6位'))
    } else if (value.length > 16) {
        callback(new Error('密码最多16位'))

    } else if (!reg.test(value)) {
        callback(new Error('密码需同时包含数字/字母/特殊符号，两种及以上组合'))

    } else {
        callback()
    }
}

const checkPhone = (rule:any,value:any,callback:any) => {
    let reg = /^1[0-9]{10}$/;
    
    if (value === '') {
        callback(new Error('请输入手机号'))
    } else if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
    } else {
        callback()
    }
}

const formRules = reactive<FormRules>({
    account:[{required:true,message:'请输入账号名'},{max:10,message:'最多只能10个文字'}],
    password:[{required:true, validator: checkPassword}],
    name:[{required:true, message:'请输入姓名'}],
    mobile:[{required:true, validator:checkPhone, trigger:'blur'}],
    role_list:[{required:true, message:'请选择角色', trigger:'change'}]
})

const props = defineProps<{
    dialogVisible:boolean,
    id?:number,
    state:string,
    departTree?:[]
}>();

const roleList = ref<any>([])

const departList = ref([])

const visible = ref(false)

watch(() => props.dialogVisible, async (val) => {
    visible.value = val
    console.log(props.state)
    if (visible.value === true) {
        await nextTick()
        if (props.state == 'edit') {
            if (props.id) {
                getDetail(props.id)
            }
        } else {
            formRef.value?.resetFields()
            form.value.id = undefined

        }
        
    }
},{
    immediate:true
})

const title = computed(() => {
    return props.state == 'add' ? '新增子账号' : '编辑子账号'
})

const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            saveAccount(form.value).then((res:any) => {
                ElMessage.success('操作成功')
                emits('success')
            })
        } else {
            console.log('error submit', fields)
        }
    }) 
}

const getDetail = (id:number) => {
    getAccountDetail({id}).then((res:any) => {
        form.value = res
    })
}

const getRoleData = () => {
    getRoleList().then((res:any) => {
        roleList.value = res
    })
}

const getDepartData = () => {
    getDepartList().then((res:any) => {
        departList.value = res
    })
}

onMounted(() => {
    // getRoleData()
    // getDepartData()
})
</script>